package com.mxpio.erp.sales.controller;

import java.io.UnsupportedEncodingException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.mxpio.erp.common.sales.entity.Address;
import com.mxpio.erp.common.sales.entity.Customer;
import com.mxpio.erp.common.sales.service.CustomerService;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.policy.CrudContext;
import com.mxpioframework.jpa.policy.impl.SmartCrudPolicyAdapter;
import com.mxpioframework.jpa.query.Criteria;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;

@Tag(name = "CustomerController", description = "客户数据接口")
@RestController
@RequestMapping("/erp/sales/cst/")
public class CustomerController {

    @Autowired
    private CustomerService customerService;

    @GetMapping("list")
    @Operation(summary = "客户列表", description = "获取客户列表（无分页）", method = "GET")
    public Result<List<Customer>> list(Criteria criteria) throws UnsupportedEncodingException {
        List<Customer> customers = customerService.list(Customer.class, criteria);
        return Result.OK(customers);
    }

    @GetMapping("page")
    @Operation(summary = "客户列表", description = "获取客户列表（分页）", method = "GET")
    public Result<Page<Customer>> page(Criteria criteria, Integer pageSize, Integer pageNo) throws UnsupportedEncodingException {
        Pageable page = PageRequest.of(pageNo-1, pageSize);
        Page<Customer> customers = customerService.listPage(Customer.class, page, criteria);
        return Result.OK(customers);
    }

    @GetMapping("list/{pnCode}")
    @Operation(summary = "根据pnCode获取客户", description = "根据pnCode获取客户", method = "GET")
    public Result<Customer> getById(@PathVariable(name = "pnCode", required = true) String pnCode) {
        Customer customer = customerService.getById(Customer.class, pnCode);
        return Result.OK(customer);
    }

    @PostMapping("add")
    @Operation(summary = "新增客户", description = "新增客户", method = "POST")
    public Result<Customer> add(@RequestBody Customer customer) {
        customerService.save(customer);
        return Result.OK(customer);
    }
    
    @RequestMapping("save")
    @Operation(summary = "保存客户", description = "保存客户")
    public Result<Customer> save(@RequestBody Customer customer) {
    	customerService.save(customer,new SmartCrudPolicyAdapter(){
        	@Override
        	public boolean beforeInsert(CrudContext context) {
        		Object o = context.getEntity();
        		if(o instanceof Address){
        			Customer customer = context.getParent();
                    ((Address) o).setPnCode(customer.getPnCode());
        		}
        		return true;
        	}
        });
        return Result.OK(customer);
    }

    @PutMapping("edit")
    @Operation(summary = "编辑客户", description = "编辑客户", method = "PUT")
    public Result<Customer> edit(@RequestBody Customer customer) {
        customerService.update(customer);
        return Result.OK(customer);
    }
    
    @PutMapping("assign/{username}/{pnCodes}")
    @Operation(summary = "批量分配业务员", description = "批量分配业务员", method = "PUT")
    public Result<Object> assign(@Parameter(description="用户名") @PathVariable(name = "username", required = true) String username,
    		@Parameter(description="客户编码，逗号分隔") @PathVariable(name = "pnCodes", required = true) String pnCodes) {
        customerService.assign(username, pnCodes);
        return Result.OK();
    }
    
    @PutMapping("transfer/{fromUser}/{toUser}")
    @Operation(summary = "业务员转移", description = "业务员转移", method = "PUT")
    public Result<Object> transfer(@Parameter(description="原业务员") @PathVariable(name = "fromUser", required = true) String fromUser,
    		@Parameter(description="新业务员") @PathVariable(name = "toUser", required = true) String toUser) {
        customerService.transfer(fromUser, toUser);
        return Result.OK();
    }

    @DeleteMapping("remove/{pnCodes}")
    @Operation(summary = "根据pnCode删除客户", description = "删除客户", method = "DELETE")
    public Result<Customer> remove(@PathVariable(name = "pnCodes", required = true) String pnCodes) {
        String[] pnCode = pnCodes.split(",");
        for(String key : pnCode){
            customerService.remove(Customer.class, key);
        }
        return Result.OK();
    }
}
